using System;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using FormsGenerator.DataAccess;

namespace FormsGenerator
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	public partial class WebForm1 : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Button NewForm;
		protected System.Data.DataView dataViewForms;

		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			if (!IsPostBack)
			{
				Render();
			}

			if (Session["ErrorMessage"] != null)
			{
				LabelErrorMessage.Text += (string) Session["ErrorMessage"];
				LabelErrorMessage.Visible = true;
				Session["ErrorMessage"] = null;
			}
		}

		private void Render()
		{
			if (Session["ShowHelp"] != null && !(bool) Session["ShowHelp"])
			{
				PanelInstructions.Visible = false;
			}
			else
			{
				PanelInstructions.Visible = true;
			}
			DataTable dtForms = DBFactory.Instance.DBHandlerInstance().GetForms(HttpContext.Current.User.Identity.Name);
			dtForms.TableName = "Forms";
			dataViewForms.Table = dtForms;
			dataViewForms.Sort = "CreatedDate DESC";
			DataGridForms.DataSource = dataViewForms;
			DataGridForms.DataBind();
		}

		#region Web Form Designer generated code

		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.dataViewForms = new System.Data.DataView();
			((System.ComponentModel.ISupportInitialize) (this.dataViewForms)).BeginInit();
			this.DataGridForms.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGridForms_ItemCommand);
			this.DataGridForms.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGridForms_EditCommand);
			this.DataGridForms.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGridForms_DeleteCommand);
			this.DataGridForms.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGridForms_ItemDataBound);
			((System.ComponentModel.ISupportInitialize) (this.dataViewForms)).EndInit();

		}

		#endregion

		private void DataGridForms_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			//LabelDebug.Text += "<br />Itemtype: " + e.Item.ItemType ;
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				//LabelDebug.Text += ", " + ((DataRowView)e.Item.DataItem)["guid"] + " - " + ((DataRowView)e.Item.DataItem)["lockedby"];
				//If Form is locked by someone else than the user logged in 
				if (!(((DataRowView) e.Item.DataItem)["lockedby"].Equals(DBNull.Value) || ((string) ((DataRowView) e.Item.DataItem)["lockedby"]).Trim().Equals("") || ((string) ((DataRowView) e.Item.DataItem)["lockedby"]).ToLower().Equals(HttpContext.Current.User.Identity.Name.ToLower())))
				{
					((LinkButton) e.Item.Cells[5].Controls[1]).Visible = true;
					((LinkButton) e.Item.Cells[5].Controls[1]).Text = "[View]";
					((LinkButton) e.Item.Cells[5].Controls[3]).Visible = false;
					Label lockedBy = (Label) e.Item.Cells[5].Controls[11]; //Label
					lockedBy.Text = "Locked by: " + ((DataRowView) e.Item.DataItem)["lockedby"];
					lockedBy.Visible = true;

					/*
					 * LabelDebug.Text += "<br />" + e.Item.ItemType.ToString() +
						" - " + ((DataRowView)e.Item.DataItem)["owner"] +
						""; //" - " + ((Label)e.Item.Cells[4].Controls[1]).Text;
						*/
					//((LinkButton)e.Item.Cells[4].Controls[2]).NavigateUrl = "EditForm.aspx?id=" + ((DataRowView)e.Item.DataItem)["guid"];
				}
				else if (!(((DataRowView) e.Item.DataItem)["lockedby"].Equals(DBNull.Value) || ((string) ((DataRowView) e.Item.DataItem)["lockedby"]).Trim().Equals("")) && ((string) ((DataRowView) e.Item.DataItem)["lockedby"]).ToLower().Equals(HttpContext.Current.User.Identity.Name.ToLower()))
				{
					((LinkButton) e.Item.Cells[5].Controls[1]).Visible = true; // Edit
					((LinkButton) e.Item.Cells[5].Controls[3]).Visible = true; // Delete
					((LinkButton) e.Item.Cells[5].Controls[3]).Attributes["onClick"] = "return confirm(\"Are you sure you want to delete the Form?\")";
					((HyperLink) e.Item.Cells[5].Controls[7]).Visible = true; // Access
					((HyperLink) e.Item.Cells[5].Controls[7]).Attributes["onClick"] = "window.open('FormAccess.aspx?id=" + e.Item.Cells[0].Text + "', 'formaccess', 'toolbar=no,titlebar=no,resizable=yes,width=400,height=400,scrollbars=yes')";
					((LinkButton) e.Item.Cells[5].Controls[9]).Visible = true; // UnLock
				}
				else
				{
					((LinkButton) e.Item.Cells[5].Controls[5]).Visible = true; //Lock					
				}

                if (DisplayResults)
                {
                    e.Item.Cells[5].Visible = true;
                    HyperLink linkResults = e.Item.FindControl("HyperLinkResults") as HyperLink;
                    linkResults.Attributes["onClick"] = "window.open('FormResults.aspx?id=" + e.Item.Cells[0].Text + "', 'results', 'toolbar=no,titlebar=no,resizable=yes,width=800,height=600,scrollbars=yes');";
                }
			}
		}

		private void DataGridForms_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			string guid = e.Item.Cells[0].Text;
			//LabelDebug.Text = "Pushed Delete";
			try
			{
				DBFactory.Instance.DBHandlerInstance().DeleteForm(guid, HttpContext.Current.User.Identity.Name);
			}
			catch (Exception ex)
			{
				LabelErrorMessage.Text += ex.Message;
				LabelErrorMessage.Visible = true;
			}

			finally
			{
				Render();
			}
		}

		private void DataGridForms_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			//LabelDebug.Text += "<br />" +  ;
			string guid = e.Item.Cells[0].Text;
			//Use Server.Transfer to support Reverse proxy. Do not use Response.Redirect!
			Server.Transfer("EditForm.aspx?id=" + guid);
		}

		private void DataGridForms_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			string guid = e.Item.Cells[0].Text;
			if (e.CommandName.ToLower().Equals("lock"))
			{
				try
				{
					DBFactory.Instance.DBHandlerInstance().LockForm(guid, HttpContext.Current.User.Identity.Name);
				}
				catch (Exception ex)
				{
					LabelErrorMessage.Text += ex.Message;
					LabelErrorMessage.Visible = true;
				}
				finally
				{
					Render();
				}
			}
			else if (e.CommandName.ToLower().Equals("unlock"))
			{
				try
				{
					DBFactory.Instance.DBHandlerInstance().UnLockForm(guid, HttpContext.Current.User.Identity.Name);
				}
				catch (Exception ex)
				{
					LabelErrorMessage.Text += ex.Message;
					LabelErrorMessage.Visible = true;
				}
				finally
				{
					Render();
				}
			}
			else
			{
				//LabelDebug.Text = "Pushed " + e.CommandName + " on " + guid;
			}

		}

        protected bool DisplayResults
        {
            get
            {
                return true;
            }
        }

		protected override bool OnBubbleEvent(object sender, EventArgs e)
		{
			Render();
			return true;
		}
	}
}